import React, { Component } from "react";
import { Toast, NoticeBar, InputItem, Modal } from "antd-mobile";
const alert = Modal.alert;
import "./xhdLoan.scss";
import { connect } from "react-redux";
import { InterfaceG, agreements_url } from "../../../config/Config";
import yhTools from "../../../tools/yh";
import XFButton from "../../../xfCompontent/xfButton/xfButton";
import SendMSGCode from "../../../component/sendMSGCode/sendMSGCode";
import MainLayout from "../../../component/mainLayout/mainLayout";
import { setRepaymentMoney } from "../../../Redux/Action/repayment/repaymentMoney";
import BackModal from "../../../component/backModal/index";
import { getSelectedBankList } from "../../../Redux/Action/bank/bank";
import iconClose from "../../../images/icon-open-account-close.png";
import Tags from "./components/Tags";
import AgreeItem from "./components/agreeItem";
const backHomeMap = {
	601: "/xhfHomeNoCredit",
	802: "/xhdHome",
	1: "/walletHome"
};
class XhfLoan extends Component {
	constructor(props) {
		super(props);
		this.state = {
			infoMoney: "",
			isVisible: false,
			loop: true,
			channelCode: "ll",
			availableAmount: "",
			allAvailableAmount: "",
			showMsgBox: false,
			loanTerm: "",
			loanInfo: {},
			isShowModal: false,
			showInfo: true,
			infoMoneryShow: true,
			inputMonery: null,
			showModal: false,
			isArgee: false,
			isDisabled: false,
			btnText: "确认借款",
			dates: [],
			showPeriodsModal: false,
			loanBalanceAmt: 0 //在贷
			// dates: [{ time: '6期', isSelected: false, loanTerm: 6 }, { time: '12期', isSelected: true, loanTerm: 12 }, { time: '18期', isSelected: false, loanTerm: 18 }],
		};
		this.timer = null;
		this.timer1 = null;
		this.mdAlart = null;
	}

	componentDidMount() {
		this.props._setRepaymentMoney({ totalLoanFee: null, type: "" });
		const { channelCode } = this.state;
		const { getSelectedBankList } = this.props;
		if (this.props.location.state.fromUrl == "xhdHome") {
			this.setState({
				showInfo: false
			});
		}
		getSelectedBankList({
			channelCode
		});
		this.xhdBorrowInitInfo();
	}
	//小辉贷初始化
	xhdBorrowInitInfo() {
		let objs = {
			url: InterfaceG.xhdBorrowInitInfo,
			params: {},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			console.log("res===", res);
			if (res.code === "0") {
				const data = res.data || {};
				const allAvailableAmount = data.availableAmount || 0;
				let strBefore = data.availableAmount || 0;
				//转化为字符串
				let strAfter = strBefore + "";
				let availableAmount = strAfter.replace(/,/g, "");
				if (availableAmount > 40000) {
					availableAmount = "40000";
				}
				const dates = data.duringtion || [];
				const btnQuickAmts = data.btnQuickAmts || [];
				const reminder = data.reminder;
				const loanBalanceAmt = data.loanBalanceAmt;
				let loanTerm = "";
				dates.some(item => {
					if (item.selected) {
						loanTerm = item.loanTerm;
					}
				});
				this.setState({
					availableAmount,
					allAvailableAmount,
					dates,
					reminder,
					loanTerm,
					loanBalanceAmt,
					btnQuickAmts
				});
			} else {
				Toast.info(res.message, 2);
			}
			Toast.hide();
		});
	}
	getInputValue(v) {
		console.log("v111111", v);
		const _this = this;
		this.setState({
			inputMonery: v
		});
		this.timer && clearTimeout(this.timer);
		if (!_this.inputRule(v)) {
			_this.setState({
				showInfo: false
			});
		} else {
			this.setState(
				{
					inputMonery: v
				},
				() => {
					if (this.isMoreFive()) {
						this.setState({
							infoMoney: "稍后可能会跟您进行电话核实，请注意接听",
							infoMoneryShow: false
						});
					}
					console.log("this.state.inputMonery", this.state.inputMonery);
				}
			);

			this.timer = setTimeout(() => {
				_this.loanTrailNew(v, _this.state.loanTerm);
			}, 2000);
		}
	}
	//点击全借
	onALlBroww = () => {
		let availableAmount = this.state.availableAmount.replace(/,/g, "");
		availableAmount = Number(availableAmount);
		this.setState(
			{
				inputMonery: availableAmount
			},
			() => {
				if (!this.inputRule(availableAmount)) {
					this.setState({
						showInfo: false
					});
				} else {
					this.loanTrailNew(availableAmount, this.state.loanTerm);
				}
			}
		);
	};
	//判断输入值的规则
	inputRule(v) {
		let value = v - 0;
		console.log("11111111", v);
		this.setState({
			infoMoneryShow: true
		});
		if (value) {
			if (value < 500) {
				this.setState({
					infoMoney: "单笔借款金额最低500元",
					infoMoneryShow: false
				});
				return false;
			} else if (value % 100) {
				this.setState({
					infoMoney: "输入金额必须为100的整数倍",
					infoMoneryShow: false
				});
				return false;
			} else if (this.state.allAvailableAmount.replace(/,/g, "") - 0 < value) {
				this.setState({
					infoMoney: "输入金额必须小于可用额度",
					infoMoneryShow: false
				});
				return false;
			} else if (value > 40000) {
				this.setState({
					infoMoney: "单笔借款金额最高4万",
					infoMoneryShow: false
				});
				return false;
			} else {
				return true;
			}
		}
	}

	//借款试算
	loanTrailNew(loanAmt, loanTerm) {
		let objs = {
			url: InterfaceG.xhdLoanTrailNew,
			params: {
				loanTerm,
				loanAmt,
				rtnType: "10",
				lnid: this.props.getAppPlatformsDatas.lnid,
				applyNo: this.props.getAppPlatformsDatas.applyNo
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				Toast.hide();
				this.setState({
					loanInfo: res.data,
					showInfo: true
				});
			} else {
				Toast.hide();
				Toast.info(res.message, 2);
			}
		});
	}

	//借款风险审核决策  "9,000.00"
	riskCheckNew(code) {
		const _this = this;
		let objs = {
			url: InterfaceG.wealth_xhd_xhdRiskCheck,
			params: {
				loanTerm: this.state.loanTerm,
				loanAmt: this.state.inputMonery,
				rtnType: "10",
				jkUsageCode: "个人日常消费",
				bankAccountNo: this.props.bankReducer.selectedBankCard.cardNo
					? this.props.bankReducer.selectedBankCard.cardNo
					: this.props.bankReducer.selectedBankList[0].cardNo,
				bankCode: this.props.bankReducer.selectedBankCard.bindCardNo
					? this.props.bankReducer.selectedBankCard.bindCardNo
					: this.props.bankReducer.selectedBankList[0].bindCardNo,
				checkCode: code,
				lnid: this.props.getAppPlatformsDatas.lnid,
				applyNo: this.props.getAppPlatformsDatas.applyNo,
				availableAmount: this.state.availableAmount.replace(/,/g, ""),
				userDeviceInfo: JSON.stringify(
					this.props.getAppPlatformsDatas.devicesInfo
				)
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				Toast.hide();
				_this.setState({
					showMsgBox: false
				});
				this.props.history.push({
					pathname: "/xhdLoanResult",
					state: {
						message: res.data.tip,
						isMoreFive: this.isMoreFive()
					}
				});
				// _this.submitNewLoanApplyResult(res.data.cino);
			} else if (res.code === "100060") {
				_this.setState({
					showMsgBox: false
				});
				Toast.hide();
				Toast.info(res.message, 2);
			} else if (res.code === "100061") {
				_this.setState({
					showMsgBox: false
				});
				_this.mdAlart = alert(
					"温馨提示",
					<div>
						<p style={{ textAlign: "center", color: "#666666" }}>
							您当前有待还款的借款
						</p>
						<p style={{ textAlign: "center", color: "#666666" }}>
							请还款后再申请新的借款
						</p>
					</div>,
					[
						{ text: "取消", onPress: () => console.log("cancel") },
						{
							text: "去还款",
							onPress: () => {
								_this.handleGoRepay();
							}
						}
					]
				);
			} else {
				Toast.hide();
				Toast.info(res.message, 2);
			}
		});
	}

	handleGoRepay = () => {
		this.mdAlart.close();
		this.props.history.push("xhdPayBackHome");
	};

	//款借款审核结果提交
	submitNewLoanApplyResult(cino) {
		const _this = this;
		let objs = {
			url: InterfaceG.xhdSubmitNewLoanApplyResult,
			params: {
				cino,
				lnid: this.props.getAppPlatformsDatas.lnid,
				applyNo: this.props.getAppPlatformsDatas.applyNo
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				Toast.hide();
				//借款成功
				_this.setState({
					showMsgBox: false
				});
				this.props.history.push({
					pathname: "/xhdLoanResult",
					state: {
						message: res.data.tip,
						isMoreFive: this.isMoreFive()
					}
				});
			} else {
				Toast.hide();
				Toast.info(res.message, 2);
			}
		});
	}

	//判断在贷和当前输入的加起来大于5万
	isMoreFive() {
		let { inputMonery, loanBalanceAmt } = this.state;
		loanBalanceAmt = loanBalanceAmt.replace(/,/g, "");
		const allAmt = Number(inputMonery) + Number(loanBalanceAmt);
		console.log("inputMonery===", inputMonery);
		console.log("allAmt===", allAmt);
		return allAmt >= 50000;
	}

	agree(e) {
		this.setState({
			isArgee: e.target.checked
		});
	}

	gotoContract() {
		// this.props.history.push("/Individualloancontract");
		this.props.history.push({
			pathname: "/iframeAgreements",
			state: {
				src: agreements_url + "/xhdLoanContract.html",
				title: "个人借款合同"
			}
		});
	}

	btnFn() {
		const { isArgee } = this.state;
		if (!this.props.bankReducer.selectedBankCard.bankName) {
			if (!this.props.bankReducer.selectedBankList.length) {
				Modal.alert("", "请先绑定银行卡", [
					{ text: "取消", onPress: () => {} },
					{
						text: "去绑卡",
						onPress: () => {
							this.props.history.push(`/xhdAddBank`);
						}
					}
				]);
				return false;
			}
		}
		if (!isArgee) {
			Toast.info("请先同意并勾选协议");
			return false;
		}
		const _this = this;
		this.timer1 && clearTimeout(this.timer1);
		this.timer1 = setTimeout(() => {
			_this.sendYzm();
		}, 1000);
	}

	selectDate(i, loanTerm) {
		let { dates, inputMonery } = this.state;
		this.loanTrailNew(inputMonery, loanTerm);
		dates.forEach((item, index) => {
			if (i == index) {
				item.selected = true;
			} else {
				item.selected = false;
			}
		});
		this.setState({
			dates,
			loanTerm
		});
	}

	showPayBackPlan() {
		this.setState({
			showModal: true
		});
	}

	closeModal() {
		this.setState({
			showModal: false
		});
	}

	// 打开 期数弹框
	showPeriods() {
		this.setState({
			showPeriodsModal: true
		});
	}
	hidePeriods() {
		this.setState({
			showPeriodsModal: false
		});
	}

	handleModalBtn(type) {
		this.setState({
			isShowModal: false
		});
		if (type == "live") {
			this.props.history.push("/xhdHome");
		}
	}

	//绑定银行卡
	gotoBink() {
		this.props.history.push("xhdBankList");
	}

	//提交回调
	submitCode(code) {
		this.riskCheckNew(code);
	}
	changePeriods(item) {
		this.setState({
			loanTerm: item.loanTerm,
			showPeriodsModal: false
		});
		this.loanTrailNew(this.state.inputMonery, item.loanTerm);
	}

	//短信验证码验证接口
	sendYzm() {
		const _this = this;
		let objs = {
			url: InterfaceG.xhdSendVerifyCode,
			params: {
				lnid: this.props.getAppPlatformsDatas.lnid,
				applyNo: this.props.getAppPlatformsDatas.applyNo
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code == "0") {
				//
				_this.sendCode.countdown();
				_this.setState({
					sendSuccessPhone: res.data.sendSuccessPhone,
					showMsgBox: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}

	//关闭验证码弹框
	closeSendModal() {
		this.setState({
			showMsgBox: false
		});
	}

	handleModal() {
		this.setState({
			isVisible: true
		});
	}

	onModalClick = booleanValue => {
		this.setState({
			isVisible: false
		});
		!booleanValue &&
			this.props.history.push(
				backHomeMap[this.props.getAppPlatformsDatas.lnid]
			);
	};
	//快捷设置
	setInputMonery = value => {
		if (value === this.state.inputMonery) return;
		this.setState({
			inputMonery: value
		});
		this.loanTrailNew(value, this.state.loanTerm);
	};
	render() {
		// const availableAmount = this.props.location.state.availableAmount;
		const selectedBankList = this.props.bankReducer.selectedBankList;
		let {
			isDisabled,
			loanTerm,
			btnText,
			dates,
			showModal,
			inputMonery,
			showInfo,
			infoMoneryShow,
			loanInfo,
			showMsgBox,
			sendSuccessPhone = "",
			reminder = "",
			availableAmount,
			allAvailableAmount,
			showPeriodsModal,
			btnQuickAmts,
			infoMoney
		} = this.state;
		let _pageParams = {
			header: {
				title: "借款",
				goBackPath: "/xhdHome"
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles,
			isModal: true,
			fromUrl: "xhdLoan"
		};
		const btnStyle = {
			borderRadius: "0.4rem"
		};
		const bankName = this.props.bankReducer.selectedBankCard.bankName || "";
		const cardNo = this.props.bankReducer.selectedBankCard.cardNo || "";
		return (
			<MainLayout
				handleBack={this.handleModal.bind(this)}
				pageParams={_pageParams}
			>
				<div className="xhd-loan">
					<div className="xhd-loan-box">
						<div className="xhd-loan-tips">
							<NoticeBar
								marqueeProps={{
									loop: true,
									trailing: 8000,
									fps: 100,
									style: {
										padding: "0 7.5px",
										WebkitBackfaceVisibility: "hidden"
									}
								}}
							>
								{reminder}
							</NoticeBar>
						</div>
						<div className="xhd-loan-input">
							{showInfo ? (
								<div className="xhd-loan-tip">借多少(元)</div>
							) : (
								<div className="xhd-loan-tip-title">
									<p>借多少(元)</p>
									<span>可借金额 {allAvailableAmount}</span>
								</div>
							)}
							<div className="input-box">
								<InputItem
									// onKeyUp = {this.debounce(this.handel.bind(this),1000)}
									onChange={this.getInputValue.bind(this)}
									value={inputMonery}
									type="money"
									moneyKeyboardAlign="left"
									placeholder={
										availableAmount >= 40000
											? `单笔最高可借40000`
											: `最高可借${availableAmount}`
									}
									extra={<span onClick={this.onALlBroww}>全借</span>}
									clear
									disabledKeys={["."]}
								>
									¥
								</InputItem>
							</div>
							{infoMoneryShow ? (
								<div>
									<Tags
										availableAmount={availableAmount}
										btnQuickAmts={btnQuickAmts}
										onClick={this.setInputMonery}
									/>
									<p className="input-monery-tip">
										单笔500元起借，且为100的整数
									</p>
								</div>
							) : (
								<p className="info-monery">{infoMoney}</p>
							)}
						</div>
						<div style={{ display: showInfo ? "block" : "none" }}>
							<div className="xhd-bind-info">
								<div className="back-shandow">
									<div className="xf-card-item">
										<div className="item-name">借多久</div>
										<div
											className="item-content"
											onClick={this.showPeriods.bind(this)}
										>
											{loanTerm ? `${loanTerm}期` : ""}
											<span> &gt; </span>
										</div>
									</div>
								</div>
								<div className="back-shandow">
									<div className="xf-card-item">
										<div className="item-name">起止日期</div>
										<div className="item-content">
											{loanInfo.startDate}至{loanInfo.endDate}
										</div>
									</div>
									<div className="xf-card-item">
										<div className="item-name">还款日</div>
										<div className="item-content">
											<span className="item-content-value">
												每月{loanInfo.paymentDay}日
											</span>
										</div>
									</div>
									<div className="xf-card-item">
										<div className="item-name">还款计划</div>
										<div
											className="item-content"
											onClick={this.showPayBackPlan.bind(this)}
										>
											{loanInfo.firstPaymentDate}{" "}
											<span className="item-content-value">
												应还
												{loanInfo.planList ? loanInfo.planList[0].refundAmt : 0}
											</span>{" "}
											&gt;
										</div>
									</div>
									<div className="xf-card-item">
										<div className="item-name">总利息</div>
										<div className="item-content">
											<span className="item-content-value">
												{loanInfo.interestAmt}
											</span>
										</div>
									</div>
								</div>
								<div className="back-shandow">
									<div className="xf-card-item account">
										<div className="item-name">收款账户</div>
										<div
											className="item-content"
											onClick={this.gotoBink.bind(this)}
										>
											{bankName ? (
												bankName + `(${cardNo})`
											) : selectedBankList.length ? (
												selectedBankList[0].bankName +
												"(" +
												selectedBankList[0].cardNo +
												")"
											) : (
												<i style={{ color: "#ff3635" }}>未绑卡</i>
											)}
											<span> &gt; </span>
										</div>
									</div>
								</div>
								<div className="back-shandow">
									<div className="xf-card-item">
										<div className="item-name">借款用途</div>
										<div className="item-content">个人日常消费</div>
									</div>
								</div>
							</div>
							<div className="loan_bottom">
								<AgreeItem
									className="loan_agree"
									onChange={this.agree.bind(this)}
								>
									阅读并同意
									<i onClick={this.gotoContract.bind(this)}>《个人借款合同》</i>
								</AgreeItem>
								<div className="xhf-loan-btn">
									<XFButton
										btnStyle={btnStyle}
										isDisabled={isDisabled}
										handleBtn={this.btnFn.bind(this)}
										btText={btnText}
									/>
								</div>
							</div>
						</div>
					</div>
					{/* <XFModal handleBtn={this.handleModalBtn.bind(this)} isShowModal={isShowModal} /> */}
					<SendMSGCode
						ref={ref => {
							this.sendCode = ref;
						}}
						getYZMCode={this.sendYzm.bind(this)}
						sendSuccessPhone={sendSuccessPhone}
						submitCode={this.submitCode.bind(this)}
						closeSendModal={this.closeSendModal.bind(this)}
						showMsgBox={showMsgBox}
					/>

					<Modal
						className="payBackPlan"
						popup
						visible={showModal}
						// onClose={this.onClose('modal2')}
						animationType="slide-up"
					>
						<div className="payBack-play-box">
							<div className="payBack-play-heard">
								<h2>等额本息</h2>
								<img onClick={this.closeModal.bind(this)} src={iconClose} />
								{/* <i onClick={this.closeModal.bind(this)}>X</i> */}
							</div>
							{loanInfo.planList
								? loanInfo.planList.map((item, index) => {
										return (
											<div key={index} className="payBack-item">
												<div className="payBack-item-l">
													<h3>{item.peri}期</h3>
													{item.refundDate}
												</div>
												<div className="payBack-item-line">
													<i></i>
												</div>
												<div className="payBack-item-r">
													<h3>{item.refundAmt}</h3>
													<p>
														含本金{item.refundPrin}+利息{item.refundInt}
													</p>
												</div>
											</div>
										);
								  })
								: ""}
						</div>
					</Modal>
					<Modal
						className="PeriodsModal"
						popup
						visible={showPeriodsModal}
						animationType="slide-up"
					>
						<div className="Periods-play-box">
							{dates
								? dates.map((item, index) => {
										return (
											<div
												key={index}
												className="payBack-item"
												onClick={this.changePeriods.bind(this, item)}
											>
												<div className="payBack-item-l">
													{item.loanTerm == loanTerm ? (
														<h3 className="changed">{item.time}</h3>
													) : (
														<h3>{item.time}</h3>
													)}
												</div>
											</div>
										);
								  })
								: ""}
							<h3
								className="payBack-item-clan"
								onClick={this.hidePeriods.bind(this)}
							>
								取消
							</h3>
						</div>
					</Modal>
				</div>
				<BackModal
					product={"xhdLoan"}
					isVisible={this.state.isVisible}
					onClick={this.onModalClick}
				/>
			</MainLayout>
		);
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		getSelectedBankList: value => dispatch(getSelectedBankList(value)),
		_setRepaymentMoney: options => {
			dispatch(setRepaymentMoney(options));
		}
	};
}

const XhfLoanPage = connect(mapStateToProps, mapDispatchToProps)(XhfLoan);
export default XhfLoanPage;
